package com.zzz.robot201.mvp.ui.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.zzz.robot201.R;
import com.zzz.robot201.app.config.AppContent;
import com.zzz.robot201.di.component.DaggerDataManageComponent;
import com.zzz.robot201.mvp.contract.DataManageContract;
import com.zzz.robot201.mvp.model.api.bean.BaseBean;
import com.zzz.robot201.mvp.presenter.DataManagePresenter;
import com.zzz.robot201.mvp.ui.activity.LoginActivity;
import com.zzz.robot201.utils.SpUtils;
import com.zzz.robot201.utils.ToastUtil;
import com.zzz.robot201.widget.dialog.LoadingDialog;

import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.OnClick;

import static android.provider.Telephony.Mms.Part.FILENAME;
import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 08/10/2020 04:10
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class DataManageFragment extends BaseFragment<DataManagePresenter> implements DataManageContract.View {

    @BindView(R.id.tv_data)
    TextView tvData;
    @BindView(R.id.btn_up_data)
    Button btnUpData;
    @BindView(R.id.ll_up_app)
    LinearLayout llUpApp;

    public static DataManageFragment newInstance() {
        DataManageFragment fragment = new DataManageFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerDataManageComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_data_manage, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }
    private LoadingDialog loadingDialog;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @OnClick({ R.id.btn_up_data})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_up_data:
                String token =(String) SpUtils.get(getActivity(), AppContent.SaveInfoKey.TOKEN, "");
                if (TextUtils.isEmpty(token)){
                    ToastUtil.showToast("请登录上传");
                    startActivity(new Intent(getContext(), LoginActivity.class));
                    return;
                }

                if (mPresenter != null) mPresenter.UpData( read());
                loadingDialog = new LoadingDialog(getContext(),"上传中");
                loadingDialog.show();
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            Thread.sleep(3000);
//
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }).start();
                break;
        }
    }
    private String DIR="robot";
    // 文件读操作函数
    private String read() {

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) { // 如果sdcard存在
            File file = new File(Environment.getExternalStorageDirectory()
                    .toString()
                    + File.separator
                    + DIR
                    + File.separator
                    + FILENAME); // 定义File类对象
            if (!file.getParentFile().exists()) { // 父文件夹不存在
                file.getParentFile().mkdirs(); // 创建文件夹
            }
            Scanner scan = null; // 扫描输入
            StringBuilder sb = new StringBuilder();
            try {
                scan = new Scanner(new FileInputStream(file)); // 实例化Scanner
                while (scan.hasNext()) { // 循环读取
                    sb.append(scan.next() + "\n"); // 设置文本
                }
                return sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (scan != null) {
                    scan.close(); // 关闭打印流
                }
            }
        } else { // SDCard不存在，使用Toast提示用户
            Toast.makeText(getContext(), "读取失败，SD卡不存在！", Toast.LENGTH_LONG).show();
        }
        return null;
    }

    @Override
    public void UpData(BaseBean baseBean) {
        loadingDialog.dismiss();
        ToastUtil.showToast("上传成功");
        cleanCustomCache(Environment.getExternalStorageDirectory()
                .toString()
                + File.separator
                + DIR
                + File.separator
                + FILENAME);
    }

    public static void cleanCustomCache(String filePath) {
        deleteFilesByDirectory(new File(filePath));
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理
     *
     * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }
}
